Welcome to Computer Programming

 

For Loop Examples

  • Basic loop i going up by one from 0-9
    for (int i=0; i<10; i++)
    
  • i going up by one from a to b
    for (int i=a; i<=b; i++)
    
  • i going up by 5 from 5-50 (so i would have the values 5,10,15,...45,50)
    for (int i=5; i<=50; i=i+5)
    
  • i going down by one from 5 to 1
    for (int i=5; i>0; i--)
    

While Loop Examples

  • To keep repeating until the user enters -1
    System.out.println("Give me a number (type -1 to stop)?");
    int num=scan.nextInt();
    while (num!=-1)
    {
    	//do something with num
    	System.out.println("Give me another number (type -1 to stop)?");
    	num=scan.nextInt(); //note I dont say int, because I already declared it as int
    }